package com.party.web.web.controller.information;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.city.City;
import com.party.core.model.enterpriseservice.EpService;
import com.party.core.model.information.Information;
import com.party.core.model.information.InformationType;
import com.party.core.model.information.InformationTypeGenre;
import com.party.core.model.mall.MallCategory;
import com.party.core.service.city.ICityService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.information.IInformationService;
import com.party.core.service.information.IInformationTypeService;
import com.party.web.biz.file.FileBizService;
import com.party.web.biz.information.InformationBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.input.information.InformationInput;
import com.party.web.web.dto.output.information.InformationOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * @program: party
 * @description: 资讯控制器
 * @author: Hua Qunhao
 * @create: 2020-02-06 15:34
 */
@Controller
@RequestMapping(value = "/information/")
public class InformationController {

    Logger logger = LoggerFactory.getLogger(InformationController.class);
    @Autowired
    private IInformationTypeService informationTypeService;
    @Autowired
    private IInformationService informationService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private ICityService cityService;
    @Autowired
    private InformationBizService informationBizService;

    /**
     * 资讯分类列表
     *
     * @param informationType 类型
     * @param page            分页参数
     * @return 交互数据
     */
    @RequestMapping(value = "type/list")
    public ModelAndView listNew(InformationType informationType, Page page) {
        page.setLimit(10);
        informationType.setDelFlag(InformationType.DEL_FLAG_NORMAL);
        ModelAndView modelAndView = new ModelAndView("information/informationTypeList");
        List<InformationType> list = informationTypeService.listPage(informationType, page);
        for (InformationType itobj : list) {
            Information information = new Information();
            information.setInformationTypeId(itobj.getId());
            information.setDelFlag(Information.DEL_FLAG_NORMAL);
            List<Information> list1 = informationService.list(information);
            itobj.setInformationNum(list1.size());
        }
        modelAndView.addObject("list", list);
        modelAndView.addObject("page", page);
        modelAndView.addObject("informationType", informationType);
        return modelAndView;
    }

    /**
     * 资讯类型视图
     *
     * @param input 分类信息
     * @return 交互数据
     */
    @RequestMapping(value = "type/informationTypeView")
    public ModelAndView categoryForm(InformationType input) {
        ModelAndView modelAndView = new ModelAndView("information/informationTypeView");
        InformationType informationType1 = null;
        if (StringUtils.isNotEmpty(input.getId())) {
            informationType1 = informationTypeService.get(input.getId());
        }
        modelAndView.addObject("informationType", informationType1);

        //是否存在互助类型
        InformationType type = new InformationType();
        type.setCategory(InformationTypeGenre.INFORMATIONTYPE_CATEGORY_MUTUAL.getCode());
        List<InformationType> mutualList = informationTypeService.list(type);
        InformationType mutualType = null;
        if (mutualList.size() > 0) {
            mutualType = mutualList.get(0);
        }
        //是否存在联系类型
        type.setCategory(InformationTypeGenre.INFORMATIONTYPE_CATEGORY_JOIN.getCode());
        List<InformationType> joinList = informationTypeService.list(type);
        InformationType joinType = null;
        if (joinList.size() > 0) {
            joinType = joinList.get(0);
        }

        Map<Integer, String> categorys = InformationTypeGenre.convertMap();

        if (mutualType != null && (StringUtils.isEmpty(input.getId())
                || (StringUtils.isNotEmpty(input.getId()) && !mutualType.getId().equals(input.getId())) )) {
            categorys.remove(InformationTypeGenre.INFORMATIONTYPE_CATEGORY_MUTUAL.getCode());
        }

        if (joinType != null && (StringUtils.isEmpty(input.getId())
                || (StringUtils.isNotEmpty(input.getId()) && !joinType.getId().equals(input.getId())) )) {
            categorys.remove(InformationTypeGenre.INFORMATIONTYPE_CATEGORY_JOIN.getCode());
        }

        modelAndView.addObject("categorys",categorys);

        return modelAndView;
    }

    /**
     * 验证分类唯一性
     *
     * @param name 分类名称
     * @return
     */
    @ResponseBody
    @RequestMapping("type/verifyName")
    public AjaxResult verifyName(String name, String id) {
        if (StringUtils.isEmpty(name)) {
            return AjaxResult.error("分类名称不能为空");
        }
        InformationType informationType = new InformationType();
        informationType.setName(name.trim());
        informationType.setDelFlag(InformationType.DEL_FLAG_NORMAL);
        List<InformationType> informationTypes = informationTypeService.list(informationType);
        if (informationTypes.size() > 0 && !(informationTypes.get(0).getId().equals(id))) {
            return AjaxResult.error("分类名称已存在");
        }
        return AjaxResult.success();
    }

    /**
     * 删除分类
     *
     * @param id 分类id
     * @return
     */
    @ResponseBody
    @RequestMapping("type/delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult typeDelete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
        try {
            Information information = new Information();
            information.setInformationTypeId(id);
            information.setDelFlag(Information.DEL_FLAG_NORMAL);
            List<Information> list = informationService.list(information);
            if (list.size() > 0) {
                return AjaxResult.error("分类下存在资讯,不能直接删除");
            }
            informationTypeService.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("分类删除异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("分类删除异常");
        }
    }

    /**
     * 资讯分类保存
     *
     * @param informationType 资讯分类
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "type/save")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult save(InformationType informationType, BindingResult result) {
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }
        String memberId = RealmUtils.getCurrentUser().getId();
        try {
            if (StringUtils.isNotEmpty(informationType.getId())) {
                InformationType t = informationTypeService.get(informationType.getId());
                MyBeanUtils.copyBeanNotNull2Bean(informationType, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
                informationType.setUpdateBy(memberId);
                informationTypeService.update(t);
            } else {
                informationType.setCreateBy(memberId);
                informationTypeService.insert(informationType);
            }

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存分类异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存分类异常");
        }
    }

    /**
     * 资讯列表
     *
     * @param information
     * @param page
     * @param commonInput
     * @return
     */
    @RequestMapping(value = "list")
    public ModelAndView list(Information information, Page page, CommonInput commonInput) {
        ModelAndView mv = new ModelAndView("information/informationList");

        Map<String, Object> params = CommonInput.appendParams(commonInput);

        City city = new City();
        //获取已开放城市
        city.setIsOpen(1);
        List<City> cityList = cityService.listPage(city, null);

        InformationType informationType = new InformationType();
        informationType.setDelFlag(InformationType.DEL_FLAG_NORMAL);
        List<InformationType> informationTypes = informationTypeService.list(informationType);
        information.setDelFlag(Information.DEL_FLAG_NORMAL);
        List<Information> informationList = informationService.webListPage(information, params, page);
        List<InformationOutput> informationOutputs = LangUtils.transform(informationList, input -> {
            InformationOutput informationOutput = InformationOutput.transform(input);

            String filePath = fileBizService.getUploadCIPath(input.getMemberId(), "information");
            //  详情二维码
            String fileName = "consultation_detail_" + input.getId();
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + fileName);
            informationOutput.setQrCodeUrl(qrCodeUrl);

            //  资讯类型
            InformationType informationType_org = informationTypeService.get(informationOutput.getInformationTypeId());
            informationOutput.setInformationTypeName(informationType_org.getName());
            //  地域
            if(StringUtils.isNotEmpty(informationOutput.getCityId())){
                City city_org = cityService.get(informationOutput.getCityId());
                if(city_org!=null){
                    informationOutput.setCityName(city_org.getName());
                }
            }
            return informationOutput;
        });
        String memberId = RealmUtils.getCurrentUser().getId();
        String filePath = fileBizService.getUploadCIPath(memberId, "information");
        //  详情二维码
        String fileName = "consultation_main_" + memberId;
        String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + fileName);

        mv.addObject("qrCodeUrl", qrCodeUrl);
        mv.addObject("input", commonInput);
        mv.addObject("information", information);
        mv.addObject("list", informationOutputs);
        mv.addObject("informationTypes", informationTypes);
        mv.addObject("cityList",cityList);
        mv.addObject("page", page);
        return mv;
    }

    /**
     * 服务列表-发布/编辑
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "view")
    public ModelAndView view(String id, String pageNo) {
        ModelAndView mv = new ModelAndView("information/informationView");
        Information information = null;
        List<InformationType> informationTypes = null;
        List<City> cityList = null;
        if (StringUtils.isNotEmpty(id)) {
            information = informationService.get(id);
            if (StringUtils.isNotEmpty(information.getContent())) {
                information.setContent(StringUtils.unescapeHtml4Video2Iframe(information.getContent()));
            }
            HashSet<String> strings = new HashSet<>();
            for (String org : information.getCityId().split(",")) {
                strings.add(org);
            }
            cityList = cityService.batchList(strings, null, null);
        }
        InformationType informationType = new InformationType();
        informationType.setDelFlag(InformationType.DEL_FLAG_NORMAL);
        informationTypes = informationTypeService.list(informationType);
        mv.addObject("information", information);
        mv.addObject("informationTypes", informationTypes);
        mv.addObject("cityList", cityList);
        mv.addObject("pageNo",pageNo);
        return mv;
    }

    /**
     * 跳转至详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "detail")
    public ModelAndView detail(String id) {
        ModelAndView mv = new ModelAndView("information/informationDetail");
        Information information = informationService.get(id);
        if (StringUtils.isNotEmpty(information.getContent())) {
            information.setContent(StringUtils.unescapeHtml4Video2Iframe(information.getContent()));
        }
        mv.addObject("information", information);
        return mv;
    }

    /**
     * 删除资讯
     */
    @ResponseBody
    @RequestMapping(value = "delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
        try {
            informationService.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("资讯删除异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("资讯删除异常");
        }
    }

    /**
     * 获取城市信息(用于筛选活动，商品列表)
     *
     * @return 行业信息列表
     */
    @RequestMapping("/cityInfo")
    public ModelAndView cityInfo(City city, String cityIds, Page page) {
        page.setLimit(10);
        ModelAndView modelAndView = new ModelAndView("information/selectCity");
        //获取已开放的
        city.setIsOpen(1);
        List<City> list = cityService.listPage(city, page);
        modelAndView.addObject("list", list);
        modelAndView.addObject("page", page);
        modelAndView.addObject("cityIds", cityIds);

        boolean isAllselect = false;

        Set<String> allCategoryIds = Sets.newHashSet();
        if (StringUtils.isNotEmpty(cityIds)) {
            allCategoryIds.addAll(Arrays.asList(cityIds.split(",")));
        }
        if (allCategoryIds.size() > 0) {
            List<City> mallCategories = cityService.batchList(allCategoryIds, new City(), null);
            mallCategories = LangUtils.transform(mallCategories, input -> {
                City category = new City();
                category.setId(input.getId());
                category.setName(input.getName());
                return category;
            });

            isAllselect = mallCategories.containsAll(list);

            modelAndView.addObject("cityJson", JSONObject.toJSONString(mallCategories));
        } else {
            modelAndView.addObject("cityJson", JSONObject.toJSONString(new ArrayList<MallCategory>()));
        }
        modelAndView.addObject("isAllselect", isAllselect);
        return modelAndView;
    }

    /**
     * 资讯保存
     *
     * @param information
     * @param result
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "save")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult save(InformationInput information, BindingResult result) {

        String memberId = RealmUtils.getCurrentUser().getId();
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }

        //检查互助类型和联系类型下是否已经存在文章
        boolean isMutualOrJoinNow = informationBizService.isMutualOrJoinType(information);
        //新增文章
        if (StringUtils.isEmpty(information.getId()) && !isMutualOrJoinNow) {
            return AjaxResult.error("该资讯类型下只能添加一篇文章");
        }
        //修改文章
        if (StringUtils.isNotEmpty(information.getId()) && !isMutualOrJoinNow) {
            Information informationOld = informationService.get(information.getId());
            if (!informationOld.getInformationTypeId().equals(information.getInformationTypeId())) {
                return AjaxResult.error("该资讯类型下只能添加一篇文章");
            }
        }

        if (StringUtils.isEmpty(information.getCityIds())) {
            information.setCityId("");
        } else {
            information.setCityId(information.getCityIds());
        }
        try {
            //内容
            if (StringUtils.isNotEmpty(information.getContent())) {
                String content = StringUtils.escapeHtml4Iframe2Video(information.getContent().trim());
                information.setContent(content);
            }
            if (StringUtils.isNotEmpty(information.getId())) {
                Information t = informationService.get(information.getId());
                MyBeanUtils.copyBeanNotNull2Bean(information, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
                informationService.update(t);
            } else {
                information.setCreateBy(memberId);
                information.setMemberId(memberId);
                informationService.insert(information);
            }

            try {
                String filePath = fileBizService.getUploadCIPath(information.getCreateBy(), "information");

                String fileName = "consultation_detail_" + information.getId();
                String content = "consultation/consultation_detail.html?id=" + information.getId();
                fileBizService.uploadCloudOut(fileName, filePath, content, information.getCreateBy());
            } catch (Exception e) {
                logger.error("上传服务二维码异常", e);
            }

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存资讯异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存资讯异常");
        }
    }

    /**
     * 生成二维码
     */
    @ResponseBody
    @RequestMapping(value = "createQrCodeUrl")
    public AjaxResult createQrCodeUrl() {
        try {
            String memberId = RealmUtils.getCurrentUser().getId();
            String filePath = fileBizService.getUploadCIPath(memberId, "information");
            String fileName = "consultation_main_" + memberId;
            String content = "consultation/consultation_main.html";
            String url = fileBizService.uploadCloudOut(fileName, filePath, content, memberId);
            return AjaxResult.success(url);
        } catch (Exception e) {
            logger.error("生成二维码异常", e);
            return AjaxResult.error("生成二维码异常"+e.getMessage());
        }
    }
}
